/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.orderpay;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.RequestHolder;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.wxlogin.WxContainer;
import shop.core.plugins.wxpay.WXPay;
import shop.core.plugins.wxpay.WXPayConfigImpl;
import shop.core.plugins.wxpay.WXPayConstants;
import shop.core.plugins.wxpay.WXPayUtil;
import shop.core.util.AddressUtils;
import shop.services.front.account.AccountService;
import shop.services.front.account.bean.Account;
import shop.services.front.brokerage.BrokerageService;
import shop.services.front.brokerage.bean.Brokerage;
import shop.services.front.offline.OfflineService;
import shop.services.front.offline.bean.Offline;
import shop.services.front.offlineAccount.OfflineAccountService;
import shop.services.front.offlineAccount.bean.OfflineAccount;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.orderdetail.bean.Orderdetail;
import shop.services.front.orderdetail.impl.OrderdetailServiceImpl;
import shop.services.front.orderpay.OrderpayService;
import shop.services.front.orderpay.bean.Orderpay;
import shop.services.front.organize.OrganizeService;
import shop.services.front.organize.bean.Organize;
import shop.services.front.product.ProductService;
import shop.services.front.product.bean.Product;
import shop.services.front.record.RecordService;
import shop.services.front.record.bean.Record;
import shop.services.front.spec.SpecService;
import shop.services.front.spec.bean.Spec;
import shop.services.front.systemSetting.SystemSettingService;
import shop.services.front.systemSetting.bean.SystemSetting;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @类名称：OrderpayController
 * @创建人：Ltz
 * @创建时间：2017-07-04 下午22:17:02
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/front/orderpay")
public class OrderpayController extends FrontBaseController<Orderpay> {
    private static final Logger logger = LoggerFactory.getLogger(OrderpayController.class);


    @Resource
    private OrderpayService orderpayService;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailServiceImpl orderdetailService;
    @Resource
    private BrokerageService brokerageService;
    @Resource
    private ProductService productService;
    @Resource
    private SystemSettingService systemSettingService;
    @Resource
    private OfflineAccountService offlineAccountService;
    @Resource
    private OrganizeService organizeService;
    @Resource
    private RecordService recordService;
    @Resource
    private AccountService accountService;
    @Resource
    private SpecService specService;
    @Resource
    private UserService userService;
    @Resource
    private OfflineService offlineservice;

    @Override
    public Services<Orderpay> getService() {
        return orderpayService;
    }

    private WXPay wxpay;
    private WXPayConfigImpl config;

    /**
     * 获取预支付信息
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPrepayId", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getPrepayId(HttpSession session, Order order) throws Exception {
        jsonResult = new JSONResult();
        order.setStatus("init");
        String type = order.getType();
        String out_trade_no = UUID.randomUUID().toString().replace("-", "");
        String orderID = "";
        DecimalFormat df = new DecimalFormat("######0.00");
//        为订单支付时插入订单
        if (type != null && type.equals("order")) {
            Account account = (Account) session.getAttribute("accountInfo");
            if (account == null)
                return JSONResult.error("您还不是志愿者，无法购物");
            String unCash = accountService.getProfit(account).getUnCash();
            String toCash = order.getToCash();
            String totalFee = order.getPtotal();
            logger.debug("订单总价：" + totalFee + "   抵扣金额：" + toCash);
            String newTotal = String.valueOf((Double.parseDouble(totalFee) - Double.parseDouble(toCash)));
            if (!StringUtils.isBlank(order.getId())) {
                logger.debug("已有订单：");
                orderID = order.getId() + "Or";
                logger.debug("订单id:" + order.getId());
                order = orderService.selectById(order.getId());
                //未成功抵扣部分回加
                String oldcashed = order.getCashed();
                account.setUnCash(String.valueOf(df.format(Double.parseDouble(account.getUnCash()) + Double.parseDouble(oldcashed))));
                accountService.update(account);
                order.setPtotal(newTotal);
                order.setCashed(toCash);
                if ((Double.parseDouble(unCash) - Double.parseDouble(toCash) < 0))
                    return JSONResult.error("抵扣金额不得超过未提现金额总数,提交失败");
                if ((Double.parseDouble(newTotal) < 0))
                    return JSONResult.error("抵扣金额不得超过订单金额总价,提交失败");
            } else {
                logger.debug("插入订单：");
                order.setPtotal(newTotal);
                order.setCashed(toCash);
                //插入交易记录表
                logger.debug("插入交易记录表");
                Record cashRecord = new Record();
                cashRecord.setMoney(order.getToCash());
                cashRecord.setUserType("1");
                cashRecord.setUserID(order.getAccountID());
                cashRecord.setTransType("5");
                recordService.insert(cashRecord);
                //扣除已提现部分
                account.setUnCash(String.valueOf(df.format(Double.parseDouble(account.getUnCash()) - Double.parseDouble(order.getToCash()))));
                accountService.update(account);
                String[] productIDs = order.getProductID().split(",");
                String[] specIDs = order.getSpecIDS().split(";");
                String[] productNumber = order.getRemark().split(",");
                for (int i = 0; i < productIDs.length; i++) {
                    logger.debug("查询产品库存：");
                    Spec spec = new Spec();
                    spec.setProductID(productIDs[i]);
                    spec.setSpecCombination(specIDs[i]);
                    spec = specService.selectOne(spec);
                    Product product1 = new Product();
                    product1.setId(productIDs[i]);
                     product1 = productService.selectOne(product1);
                    if ((spec.getSpecStock() - Integer.parseInt(productNumber[i])) < 0)
                        return JSONResult.error(product1.getName() + "库存不足，下单失败");
                }
                orderID = String.valueOf(orderService.insert(order));
                orderID = orderID + "Or";
                logger.debug("商品ID为：" + order.getProductID());
            }
        } else {
            //募捐支付时更新募捐金额
            logger.debug("更新募捐活动信息：");
            OfflineAccount offlineAccount = offlineAccountService.selectById(order.getId());
            //增加募捐活动付款标识Of
            orderID = offlineAccount.getId() + "Of";
            offlineAccount.setStatus("O");
            offlineAccount.setContributions(order.getPtotal());
            offlineAccountService.update(offlineAccount);

        }
        config = WXPayConfigImpl.getInstance();
        wxpay = new WXPay(config);
        Float ftotal_fee = Float.parseFloat(order.getPtotal()) * 100;
        String total_fee = String.valueOf(ftotal_fee.intValue());//商品总价
        logger.debug("商品总价为：" + total_fee);
        logger.debug("订单号为：" + out_trade_no);
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", "华贝生物科技");
        data.put("out_trade_no", out_trade_no);
        data.put("device_info", "");
        data.put("total_fee", total_fee);
        String clientIp = AddressUtils.getIp(RequestHolder.getRequest()).split(",")[0];
        data.put("spbill_create_ip", clientIp);
        data.put("notify_url", "http://www.kekelvxing.cn/front/orderpay/notify");
        data.put("trade_type", "JSAPI");
        data.put("product_id", UUID.randomUUID().toString().replace("-", ""));
        data.put("openid", session.getAttribute("userOpenId").toString());
        try {
            Map<String, String> r = wxpay.unifiedOrder(data);
            logger.debug("获得预支付信息为：" + r.get("return_msg") + ",获得返回状态码为：" + r.get("return_code"));
            //回传页面参数
            Map<String, String> reqData = new HashMap<String, String>();
            reqData.put("appId", config.getAppID());
            reqData.put("timeStamp", String.valueOf(new Date().getTime() / 1000));
            reqData.put("nonceStr", r.get("nonce_str"));
            reqData.put("signType", "MD5");
            reqData.put("package", "prepay_id=" + r.get("prepay_id"));
            String paySign = WXPayUtil.generateSignature(reqData, config.getKey(), WXPayConstants.SignType.MD5);
            reqData.put("paySign", paySign);
            logger.debug("回传页面参数填写完成");
//          在本地插入订单支付信息
            logger.debug("在本地插入订单支付信息");
            Orderpay orderpay = new Orderpay();
            orderpay.setOrderId(orderID);
//            获取支付记录表判断是否存在支付订单
            Orderpay anOrderpay = orderpayService.selectOne(orderpay);
            if (anOrderpay != null) {
                anOrderpay.setPrepayId(r.get("prepay_id"));
                anOrderpay.setOutTradeNo(out_trade_no);
                getService().update(anOrderpay);
                jsonResult.setData(reqData);
                jsonResult.setSuccess(true);
                return jsonResult;
            } else {
                orderpay.setPayStatus("0");
                orderpay.setPrepayId(r.get("prepay_id"));
                orderpay.setPayType(data.get("trade_type"));
                BigDecimal payAmount = new BigDecimal(order.getPtotal());
                orderpay.setPayAmount(payAmount);
                orderpay.setOutTradeNo(out_trade_no);
                orderpay.setProductBody(data.get("body"));
                getService().insert(orderpay);
//          model.addAttribute("e", reqData);
                jsonResult.setData(reqData);
                jsonResult.setSuccess(true);
                return jsonResult;
            }
        } catch (Exception e) {
            logger.debug("打印错误日志：");
            e.printStackTrace();
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }

    /**
     * 微信支付回调接口
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "notify", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String payNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader reader = null;
        reader = request.getReader();
        String line = "";
        String xmlString = null;
        StringBuffer inputString = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        request.getReader().close();
        Map<String, String> reciveData = WXPayUtil.xmlToMap(xmlString);
        logger.debug("收到支付回调结果:" + reciveData);
        String out_trade_no = reciveData.get("out_trade_no");
        Orderpay orderpay = new Orderpay();
        orderpay.setOutTradeNo(out_trade_no);
        logger.debug("查询本地支付记录");
        orderpay = getService().selectOne(orderpay);
        String orderID = orderpay.getOrderId();
        String rsType = reciveData.get("return_code");
        HashMap<String, String> data = new HashMap<String, String>();
        String reStr = "";
        if (rsType.equals("SUCCESS")) {
            if (orderID.contains("Or")) {
//                去除订单标识
                orderID = orderID.substring(0, orderID.length() - 2);
                Order order = orderService.selectById(orderID);
                if (order.getStatus().equals("pass") && order.getPaystatus().equals("y")) {
                    data.put("return_code", "SUCCESS");
                    data.put("return_msg", "OK");
                    reStr = WXPayUtil.mapToXml(data);
                    return reStr;
                } else {
                    //获取佣金比例设定
                    SystemSetting setting = systemSettingService.selectOne(new SystemSetting());
                    //设定double格式，保留两位小数
                    DecimalFormat df = new DecimalFormat("######0.00");
                    List<Double> profits = new ArrayList<>();
                    Double totalCommission = 0.00;
                    Double adminProfit = 0.00;
                    Double profit = 0.00;
                    Orderdetail orderdetail = new Orderdetail();
                    orderdetail.setOrderID(Integer.parseInt(orderID));
                    logger.debug("订单id：" + orderID);
                    List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
                    for (Orderdetail anOrdedetail : orderdetailList) {
                        Product product = new Product();
                        product.setId(anOrdedetail.getProductID());
                        logger.debug("商品规格：" + anOrdedetail.getSpecInfo());
                        product.setSpecCombination(anOrdedetail.getSpecInfo());
                        product = productService.selectBySpecCombination(product);
                        //更新产品库存
                        Spec spec = new Spec();
                        spec.setProductID(anOrdedetail.getProductID());
                        spec.setSpecCombination(anOrdedetail.getSpecInfo());
                        spec = specService.selectOne(spec);
                        Integer newStock = (spec.getSpecStock() - Integer.parseInt(anOrdedetail.getNumber()));//剩余库存
                        spec.setSpecStock(newStock);
                        specService.update(spec);
                        //计算商品利润总值
                        logger.debug("商品进价：" + product.getSpecPurchasePrice() + "    商品数量" + anOrdedetail.getNumber());
                        if (StringUtils.isBlank(product.getSpecPurchasePrice().toString())) {
                            product.setSpecPurchasePrice(new BigDecimal(0));
                        }
                        profit = product.getSpecNowPrice().subtract(product.getSpecPurchasePrice()).multiply(new BigDecimal(anOrdedetail.getNumber())).doubleValue();
                        profits.add(profit);
                        //计算需要分佣的金额
                        Double temp = profit * (Double.parseDouble(setting.getPercent()));
                        df.format(temp);
                        df.format(profit);
                        adminProfit = adminProfit + profit - temp;
                        totalCommission = totalCommission + temp;
                        Integer sellcout = product.getSellcount();

                        Integer newSellCout = Integer.parseInt(anOrdedetail.getNumber()) + sellcout;
                        product.setSellcount(newSellCout);
                        productService.update(product);
                    }
                    profit = 0.00;
                    for (Double d : profits) {
                        profit = profit + d;
                    }
//                    获取分佣类型
                    Account account = new Account();
                    account.setId(order.getAccountID());
                    account = accountService.selectOne(account);
                    String profitType = organizeService.getprofitType(order.getAccountID());
                    String money = "0.00";//志愿者分到的佣金
                    String cmoney = "0.00";//c级机构分到的佣金
                    String bmoney = "0.00";//b级机构分到的佣金
                    String amoney = "0.00";//a级机构分到的佣金
                    Map profitMap = new HashMap<String, Object>();
                    profitMap.put("order", order);
                    profitMap.put("setting", setting);
                    profitMap.put("account", account);
                    profitMap.put("totalCommission", totalCommission);
                    profitMap.put("profit", profit);
                    switch (profitType) {
                        case "c": {
                            cmoney = insertProfit(profitMap, "c");
                            //更新用户爱心钱包数据
                            logger.debug("更新机构数据：");
                            updateorganize(account, cmoney, "c");
                            break;
                        }
                        case "b": {
                            cmoney = insertProfit(profitMap, "c");
                            bmoney = insertProfit(profitMap, "b");
                            //更新用户爱心钱包数据
                            logger.debug("更新机构数据：");
                            updateorganize(account, cmoney, "c");
                            updateorganize(account, bmoney, "b");
                            break;
                        }
                        case "a": {
                            cmoney = insertProfit(profitMap, "c");
                            bmoney = insertProfit(profitMap, "b");
                            amoney = insertProfit(profitMap, "a");
                            //更新用户爱心钱包数据
                            logger.debug("更新机构数据：");
                            updateorganize(account, cmoney, "c");
                            updateorganize(account, bmoney, "b");
                            updateorganize(account, amoney, "a");
                            break;
                        }
                        default:
                            break;
                    }
                    money = insertProfit(profitMap, "d");
//                        更新用户爱心钱包数据
                    logger.debug("更新用户数据：");
                    account.setWalletMoney(String.valueOf(df.format(Double.parseDouble(account.getWalletMoney()) + Double.parseDouble(money))));
                    account.setUnCash(String.valueOf(df.format(Double.parseDouble(account.getUnCash()) + Double.parseDouble(money))));
                    accountService.update(account);
                    //更新admin佣金
                    adminProfit = adminProfit + totalCommission - Double.parseDouble(amoney) - Double.parseDouble(bmoney) - Double.parseDouble(cmoney) - Double.parseDouble(money);
                    User user = new User();
                    user.setUsername("admin");
                    user = userService.selectOne(user);
                    user.setWalletMoney(String.valueOf(df.format(adminProfit)));
                    user.setUnCash(String.valueOf(df.format(adminProfit)));
                    userService.update(user);
//                更新订单状态
                    logger.debug("更新订单状态");
                    order.setPaystatus("y");
                    order.setStatus("pass");
                    order.setProductID(null);
                    orderService.update(order);
                    //插入admin返佣
                    Brokerage brokerage = new Brokerage();
                    brokerage.setAccountID(order.getAccountID());
                    brokerage.setAffType("3");
                    brokerage.setAffID("1");
                    brokerage.setOrderID(order.getId());
                    brokerage.setMoney(String.valueOf(adminProfit));
                    brokerage.setProfit(String.valueOf(profit));
                    String Percent = setting.getPercent();
                    brokerage.setPercent(Percent);
                    brokerage.setAPercent(getNewPercent(Percent, setting.getaPercent()));
                    brokerage.setBPercent(getNewPercent(Percent, setting.getbPercent()));
                    brokerage.setCPercent(getNewPercent(Percent, setting.getcPercent()));
                    brokerage.setDPercent(getNewPercent(Percent, setting.getdPercent()));
                    brokerageService.insert(brokerage);
                }
            } else {
//                去除订单标识
                logger.debug("更新募捐活动状态");
                orderID = orderID.substring(0, orderID.length() - 2);
//                获取活动参与详情
                OfflineAccount offlineAccount = offlineAccountService.selectById(orderID);
                offlineAccount.setStatus("1");
                offlineAccountService.update(offlineAccount);
                int totalMoney = offlineAccountService.getTotal(offlineAccount);
                //更新目标金额进度
                Offline offline = new Offline();
                offline.setId(offlineAccount.getOfflineID());
                offlineservice.selectOne(offline);
                if (totalMoney >= Integer.parseInt(offline.getGoal())) {
                    offline.setStatus("4");
                    offlineservice.update(offline);
                }
                logger.debug("更新机构金额");
                Organize organize = new Organize();
                organize.setId(offlineAccount.getOrganizeID());
                organize = organizeService.selectOne(organize);
                organize.setSum(offlineAccount.getContributions());
                organize.setUnCash(offlineAccount.getContributions());
                organizeService.update(organize);
            }
//                更新本地订单支付表信息
            logger.debug("更新本地订单支付表信息");
            orderpay.setTransactionId(reciveData.get("transaction_id"));
            orderpay.setPayStatus("1");
            getService().update(orderpay);
        }
        data.put("return_code", "SUCCESS");
        data.put("return_msg", "OK");
        reStr = WXPayUtil.mapToXml(data);
        return reStr;
    }

    /**
     * 微信扫一扫测试
     *
     * @return
     */
    @RequestMapping("/toScan")
    @ResponseBody
    public JSONResult wxScan() {
        jsonResult = new JSONResult();
        String timeStamp = String.valueOf(new Date().getTime() / 1000);
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        Map resMap = new HashMap<>();
        try {
            Map<String, String> reqData = new HashMap<String, String>();
            reqData.put("jsapi_ticket", systemManager.getJsapiTicket());
            reqData.put("timestamp", timeStamp);
            reqData.put("noncestr", nonceStr);
            reqData.put("url", "http://www.kekelvxing.cn/toHome");
            String signature = WXPayUtil.generateSignature(reqData, null, WXPayConstants.SignType.SHA1);
            resMap.put("appId", WxContainer.appid);
            resMap.put("timestamp", timeStamp);
            resMap.put("noncestr", nonceStr);
            resMap.put("signature", signature);
            logger.info("获取微信参数:" + resMap);
        } catch (Exception e) {
            logger.error("获取微信jsapi参数失败:");
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取微信jsapi参数失败");
            return jsonResult;
        }
        jsonResult.setSuccess(true);
        jsonResult.setData(resMap);
        return jsonResult;
    }

    /**
     * 微信退款
     *
     * @return
     */
    @RequestMapping("/refund")
    @ResponseBody
    public JSONResult wxRefund() {
        jsonResult = new JSONResult();
        String nonceStr = UUID.randomUUID().toString().replace("-", "");

        try {
            config = WXPayConfigImpl.getInstance();
            wxpay = new WXPay(config);
            HashMap<String, String> data = new HashMap<String, String>();
            data.put("nonce_str", nonceStr);
            //退款编号和支付编号一致
            data.put("transaction_id", "4002532001201708034314168330");
            data.put("out_refund_no", "4002532001201708034314168330");
            //退款金额和支付金额一致，单位为分
            data.put("total_fee", "1");
            data.put("refund_fee", "1");
            Map<String, String> rs = wxpay.refund(data);

            if (rs.get("return_code").equals("SUCCESS")) {
                jsonResult.setSuccess(true);
                return jsonResult;
            } else {
                jsonResult.setMessage(rs.get("return_msg"));
            }
        } catch (Exception e) {
            logger.error("退款失败！" + e);
        }
        jsonResult.setSuccess(false);
        return jsonResult;
    }

    /**
     * 微信退款回调接口
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "refundNotify", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String refundNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader reader = null;
        reader = request.getReader();
        String line = "";
        String xmlString = null;
        StringBuffer inputString = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        request.getReader().close();
        Map<String, String> reciveData = WXPayUtil.xmlToMap(xmlString);
        logger.debug("收到退款回调结果:" + reciveData);


        HashMap<String, String> data = new HashMap<String, String>();
        data.put("return_code", "SUCCESS");
        data.put("return_msg", "OK");
        String reStr = WXPayUtil.mapToXml(data);
        return reStr;
    }

    private String getNewPercent(String Percent, String oPercent) {
        return String.valueOf(Double.parseDouble(Percent) * Double.parseDouble(oPercent));
    }

    /**
     * 爱心钱包、返佣记录维护方法
     *
     * @param map  必要参数表
     * @param type 分佣类型
     * @return
     */
    private String insertProfit(Map map, String type) {
        Order order = (Order) map.get("order");
        SystemSetting setting = (SystemSetting) map.get("setting");
        Double totalCommission = (Double) map.get("totalCommission");
        Double profit = (Double) map.get("profit");
        Account account = (Account) map.get("account");
        DecimalFormat df = new DecimalFormat("######0.00");
        Brokerage brokerage = new Brokerage();
        Record record = new Record();
        brokerage.setAccountID(order.getAccountID());
        switch (type) {
            case "d":
                brokerage.setAffType("1");
                brokerage.setAffID(order.getAccountID());
                record.setUserID(order.getAccountID());
                brokerage.setOrganizeName(account.getName());
                record.setUserType("1");
                break;
            case "c":
                brokerage.setAffType("2");
                record.setUserType("2");
                record.setUserID(getUserIdByOrganize(account.getOrganizeID()));
                brokerage.setAffID(account.getOrganizeID());
                break;
            case "b":
                brokerage.setAffType("2");
                record.setUserType("2");
                record.setUserID(getUserIdByOrganize(organizeService.getSupOrganize(account.getOrganizeID()).getId()));
                brokerage.setAffID(organizeService.getSupOrganize(account.getOrganizeID()).getId());
                break;
            default:
                brokerage.setAffType("2");
                record.setUserType("2");
                record.setUserID(getUserIdByOrganize(organizeService.getSupOrganize(organizeService.getSupOrganize(account.getOrganizeID()).getId()).getId()));
                brokerage.setAffID(organizeService.getSupOrganize(organizeService.getSupOrganize(account.getOrganizeID()).getId()).getId());
                break;
        }
        brokerage.setOrderID(order.getId());

        //计算返利
        String money;
        switch (type) {
            case "d":
                money = String.valueOf(df.format(totalCommission * Double.parseDouble(setting.getdPercent())));
                break;
            case "c":
                money = String.valueOf(df.format(totalCommission * Double.parseDouble(setting.getcPercent())));
                break;
            case "b":
                money = String.valueOf(df.format(totalCommission * Double.parseDouble(setting.getbPercent())));
                break;
            default:
                money = String.valueOf(df.format(totalCommission * Double.parseDouble(setting.getaPercent())));
                break;
        }
        brokerage.setMoney(money);
        brokerage.setProfit(String.valueOf(profit));
        String Percent = setting.getPercent();
        brokerage.setPercent(Percent);
        brokerage.setAPercent(getNewPercent(Percent, setting.getaPercent()));
        brokerage.setBPercent(getNewPercent(Percent, setting.getbPercent()));
        brokerage.setCPercent(getNewPercent(Percent, setting.getcPercent()));
        brokerage.setDPercent(getNewPercent(Percent, setting.getdPercent()));
        brokerageService.insert(brokerage);
        record.setMoney(money);
        record.setTransType("6");
        recordService.insert(record);
        return money;
    }

    /**
     * 更新机构爱心钱包数据
     *
     * @param account c级机构志愿者
     * @param money   更新金额
     * @param type    机构类型
     */
    private void updateorganize(Account account, String money, String type) {
        DecimalFormat df = new DecimalFormat("######0.00");
        Organize organize = new Organize();
        switch (type) {
            case "c":
                organize.setId(account.getOrganizeID());
                break;
            case "b":
                organize.setId(organizeService.getSupOrganize(account.getOrganizeID()).getId());
                break;
            default:
                organize.setId(organizeService.getSupOrganize(organizeService.getSupOrganize(account.getOrganizeID()).getId()).getId());
                break;
        }
        organize = organizeService.selectOne(organize);
        User user = new User();
        user.setUsername(organize.getPrincipalPhone());
        user = userService.selectOne(user);
        if (StringUtils.isBlank(user.getWalletMoney()))
            user.setWalletMoney("0");
        if (StringUtils.isBlank(money))
            money = "0";
        if (StringUtils.isBlank(user.getUnCash()))
            user.setUnCash("0");
        user.setWalletMoney(String.valueOf(df.format(Double.parseDouble(user.getWalletMoney()) + Double.parseDouble(money))));
        user.setUnCash(String.valueOf(df.format(Double.parseDouble(user.getUnCash()) + Double.parseDouble(money))));
        userService.update(user);
    }


    private String getUserIdByOrganize(String OrganizeId) {
        Organize organize = new Organize();
        organize.setId(OrganizeId);
        organize = organizeService.selectOne(organize);
        return organize.getUserId();
    }
}
